package com.mes.basicdata.dao;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.bstek.bdf2.core.model.DefaultUser;
import com.bstek.bdf2.core.model.UserDept;
import com.bstek.dorado.data.provider.Criteria;
import com.bstek.dorado.data.provider.Page;
import com.mes.basicdata.dao.iface.IEmployeeDao;
import com.mes.basicdata.domain.Employee;
import com.mes.common.dao.BasicDao;
import com.mes.system.dao.iface.IEmployeeRoleDao;
import com.mes.system.dao.iface.IRoleDao;
import com.mes.system.domain.EmployeeRole;
import com.mes.system.domain.Role;

@Repository
public class EmployeeDao extends BasicDao<Employee> implements IEmployeeDao{
	private static final Log log = LogFactory.getLog(EmployeeDao.class);

	@Autowired
	IRoleDao roleDao;
	
	@Override
	public Collection<Employee> getByDeptId(String deptId, Page<Employee> page){
		DetachedCriteria detachedCriteria = DetachedCriteria.forClass(Employee.class);
		detachedCriteria.add(Restrictions.eq("deptUid", deptId));
		if(page != null){
			this.pagingQuery(page, detachedCriteria);
			return page.getEntities();
		}else{
			List list = this.query(detachedCriteria, null);
			return list;
		}
		
	}

	@Autowired
	IEmployeeRoleDao employeeRoleDao;
	
	/**
	 * 获取拥有某个角色的人员列表
	 * @param roleUid 角色Uid
	 * @param page
	 * @return
	 */
	@Override
	public List<Employee> getEmployeesByRoleUid(String roleUid, Page<Employee> page) throws Exception {
		List<Employee> employees = new ArrayList<Employee>();
		
		DetachedCriteria criteria = DetachedCriteria.forClass(EmployeeRole.class);
		criteria.add(Restrictions.eq("roleUid", roleUid));
		criteria.addOrder(Order.asc("employee.employeeName"));
		if(page != null){
			Page<EmployeeRole> page1 = new Page<EmployeeRole>(page.getPageSize(), page.getPageNo());
			this.pagingQuery(page1, criteria);
			Collection<EmployeeRole> employeeRoles = page1.getEntities();
			for(EmployeeRole er : employeeRoles){
				Employee e = er.getEmployee();
				employees.add(e);
			}
			page.setEntities(employees);
			page.setEntityCount(page1.getEntityCount());
		}else{
			List<EmployeeRole> employeeRoles = employeeRoleDao.query(criteria, null);
			for(EmployeeRole er : employeeRoles){
				Employee e = er.getEmployee();
				employees.add(e);
			}
		}
		return employees;
	}
	
	/**
	 * 获取某一个部门的检验员列表，并按照人员名称排序
	 * 
	 * @param deptId
	 * @param page
	 * @return
	 * @throws Exception
	 */
	@Override
	public List<Employee> getCheckersByDeptUid(String deptUid, Criteria criteria) throws Exception {
		
		List<Employee> checkers = new ArrayList<Employee>();
		DetachedCriteria detachedCriteria = DetachedCriteria.forClass(Employee.class);
		detachedCriteria.add(Restrictions.like("deptUid", deptUid, MatchMode.START));
		detachedCriteria.addOrder(Order.asc("employeeName"));
		
		List<Employee> list = this.query(detachedCriteria, null);
		if(list != null && list.size() > 0){
			for(Employee e : list){
				List<Role> roles = roleDao.getRolesByEmployeeUid(e.getUuid());
				if(roles != null  && roles.size()>0){
					for(Role role : roles){
						if("Checker".equals(role.getUuid())){
							checkers.add(e);
							break;
						}
					}
				}
			}
		}
		return checkers;
	}
	
	@Override
	public void getEmployeeByConditions(Page<Employee> page, Map<String, Object> params) throws Exception {
		// TODO Auto-generated method stub
				Map<String, Object> args = new HashMap<String, Object>();
				StringBuffer coreHql = new StringBuffer("from "
						+ Employee.class.getName() + " a where 1=1 ");

				String employeeId = (String) params.get("employeeId");
				if (StringUtils.isNotEmpty(employeeId)) {
					coreHql.append(" and a.employeeId like :employeeId ");
					args.put("employeeId", "%" + employeeId + "%");
				}
				
				String employeeName = (String) params.get("employeeName");
				if (StringUtils.isNotEmpty(employeeName)) {
					coreHql.append(" and a.employeeName like :employeeName ");
					args.put("employeeName", "%" + employeeName + "%");
				}
				
				String countHql = "select count(*) " + coreHql.toString();
//					String hql = coreHql.toString() + "order by a.dept.id,a.id";
				String hql = coreHql.toString();
				
				Map<String, Object> newArgs = new HashMap<String, Object>();
				String key;
				String newKey;
				Iterator<String> iterator = args.keySet().iterator();
				while(iterator.hasNext()){
					key = (String)iterator.next();
					newKey = key.replace(".", "_");
					newArgs.put(newKey, args.get(key));
					hql = hql.replace(":"+key, ":"+newKey);
					countHql = countHql.replace(":"+key, ":"+newKey);
					
					System.out.println("hql: " + hql);
					System.out.println("countHql: " + countHql);
					System.out.println("newArgs: " + newArgs);
				}
				this.pagingQuery(page, hql, countHql, newArgs);
		}

	@Override
	public void saveUser(DefaultUser user) throws Exception {
		Session session = this.getSessionFactory().getCurrentSession();
		try {
			session.save(user);
		} finally {
			session.flush();
		}
		
	}

	@Override
	public void updateUser(DefaultUser user) throws Exception {
		Session session = this.getSessionFactory().getCurrentSession();
		try {
			session.update(user);
		} finally {
			session.flush();
		}
		
	}

	@Override
	public void deleteUser(DefaultUser user) throws Exception {
		Session session = this.getSessionFactory().getCurrentSession();
		try {
			session.delete(user);
		} finally {
			session.flush();
		}
		
	}

	@Override
	public void saveUserDept(UserDept userDept) throws Exception {
		Session session = this.getSessionFactory().getCurrentSession();
		try {
			session.save(userDept);
		} finally {
			session.flush();
		}
		
	}
	
	@Override
	public void updateUserDept(UserDept userDept) throws Exception {
		Session session = this.getSessionFactory().getCurrentSession();
		try {
			session.update(userDept);
		} finally {
			session.flush();
		}
		
	}

	/**
	 * 根据用户id获得部门用户关系对象
	 */
	@Override
	public UserDept getUserDeptByUser(String username) throws Exception {
		Session session = this.getSessionFactory().getCurrentSession();
		String hql = "from UserDept where username = ?";
		
		Query query = session.createQuery(hql);
		
		query.setString(0, username);
		List<UserDept> list = query.list();
		
		if (list.size() > 0){
			return (UserDept) list.get(0);
		}else {
			return null;
		}
		
	}

}
